<html>
<head>
<title>C++ Annotations Version 6.5.0</title>
</head>
<body text="black" bgcolor="white">
<hr>
<ul>
    <li> <a href="cplusplus.html">Table of Contents</a>
    <li> <a href="cplusplus01.html">Previous Chapter</a>
    <li> <a href="cplusplus03.html">Next Chapter</a>
</ul>
<hr>
<a name="IntroC"></a><a name="l2"></a>
<h1>Chapter 2: Introduction</h1>
<a name="intro"></a>
<blockquote>
    <em>
        Don't hesitate to send in feedback: send an e-mail if you like the
        C++ Annotations; if you think that important material was omitted;
        if you find errors or typos in the text or the code examples;
        or if you just feel like e-mailing. Send your e-mail to
        <a href="mailto:f.b.brokken@rug.nl">Frank B. Brokken</a>.
<p>
<strong>Please</strong> state the document version you're referring to, as found in
        the title (in this document: 6.5.0) and please state chapter and
        paragraph name or number you're referring to.
<p>
All received mail is processed conscientiously, and received
        suggestions for improvements will usually have been processed by the
        time a new version of the Annotations is released. Except for the
        incidental case I will normally not acknowledge the receipt of
        suggestions for improvements. Please don't interpret this as me not
        appreciating your efforts.
    </em>
</blockquote>
<p>
<a name="intro/intro"></a>This document offers an introduction to the <strong>C++</strong> programming language. It
is a guide for <strong>C/C++</strong> programming courses, yearly presented by Frank at the
University of Groningen. This document is not a complete <strong>C/C++</strong> handbook,
as much of the <strong>C</strong>-background of <strong>C++</strong> is not covered. Other sources
should be referred to for that (e.g., the Dutch book <em>De programmeertaal C</em>,
Brokken and Kubat, University of Groningen, 1996) or the
<a name="an3"></a>
 
 <a target=_top href="http://publications.gbdirect.co.uk/c_book/">on-line book</a> suggested to
me by George Danchev (danchev at spnet dot net).
<p>
The reader should realize that extensive knowledge of the <strong>C</strong> programming
language is actually assumed. The <strong>C++</strong> Annotations continue where topics of
the <strong>C</strong> programming language end, such as pointers, basic flow control and
the construction of functions.
<p>
The version number of the <strong>C++</strong> Annotations (currently 6.5.0) is updated when
the contents of the document change. The first number is the major number, and
will probably not be changed for some time: it indicates a major
rewriting. The middle number is increased when new information is added to the
document. The last number only indicates small changes; it is increased when,
e.g., series of typos are corrected.
<p>
This document is published by the Computing Center, University of Groningen,
the Netherlands under the <a name="an4"></a>

 <a target=_top href="http://www.gnu.org/licenses/">GNU General Public License</a>. 
<p>
The <strong>C++ Annotations</strong> were typeset using the <a name="an5"></a>

    <a name="an6"></a>

    <a target=_top href="http://yodl.sourceforge.net">yodl</a>
formatting system.
<p>
<blockquote>
    <strong>
        All correspondence concerning suggestions, additions, improvements or
        changes to this document should be directed to the author:
    </strong>
<p>
<strong>
        <center>Frank B. Brokken <br>
        Computing Center, University of Groningen <br>Nettelbosje 1,<br>P.O. Box 11044,<br>9700 CA Groningen <br>The Netherlands <br>
        (email: f.b.brokken@rug.nl)
        </center>
   </strong>
</blockquote>
<p>
In this chapter a first impression of <strong>C++</strong> is presented. A few extensions
to <strong>C</strong> are reviewed and the concepts of object based and object
oriented programming (OOP) are briefly introduced.
<p>
<a name="WHATSNEW"></a><a name="l3"></a>
<h2>2.1: What's new in the C++ Annotations</h2>
    <a name="history"></a>This section is modified when the first or second part of the version number
changes (and sometimes for the third part as well).
        
    <ul>
    <li> Version 6.5.0 changed <code>unsigned</code> into <code>size_t</code> where appropriate,
and explicitly mentioned <code>int</code>-derived types like <code>int16_t</code>. In-class
member function definitions were moved out of (below) their class definitions
as <code>inline</code> defined members. A paragraphs about implementing pure virtual
member functions was added. Various bugs and compilation errors were fixed.
    <li> Version 6.4.0 added a new section (<a href="cplusplus19.html#RETURNNESTED">19.11.2</a>) further
discussing the use of the <code>template</code> keyword to distinguish types nested
under template classes from template members. Furthermore, <a name="an7"></a>
<em>Sergio Bacchi</em>
<code> s dot bacchi at gmail dot com</code> did an impressive job when translating the
Annotations into Portuguese. His translation (which may lag a distribution or
two behind the latest verstion of the Annotations) may also be retrieved
from<br>
<a href="ftp://ftp.rug.nl/contrib/frank/documents/annotations">ftp://ftp.rug.nl/contrib/frank/documents/annotations</a>.
    <li> Version 6.3.0 added new sections about anonymous objects (section
<a href="cplusplus06.html#ANONYMOUS">6.2.1</a>) and type resolution with template classes (section
<a href="cplusplus19.html#TYPERES">19.11.1</a>). Also the description of the template parameter deduction
algorithm was rewritten (cf. section <a href="cplusplus18.html#PARDEDUCT">18.2.4</a>) and numerous
modifications required because of the compiler's closer adherence to the
<strong>C++</strong> standard were realized, among which <a name="an8"></a>
exception rethrowing from
constructor and destructor function try blocks. Also, all textual corrections
received from readers since version 6.2.4 were processed.
    <li> In version 6.2.4 many textual improvements were realized. I received
extensive lists of typos and suggestions for clarifications of the text, in
particular from Nathan Johnson and from Jakob van Bethlehem. Equally valuable
were suggestions I received from various other readers of the <strong>C++</strong>
annotations: all were processed in this release. The <strong>C++</strong> content matter of
this release was not substantially modified, compared to version 6.2.2.
    <li> Version 6.2.2 offers improved implementations of the configurable
template classes (sections <a href="cplusplus20.html#WRAPONE">20.7.3</a> and <a href="cplusplus20.html#WRAPTWO">20.7.4</a>).
    <li> Version 6.2.0 was released as an Annual Update, by the end of May,
2005. Apart from the usual typo corrections several new sections
were added and some were removed: in the Exception chapter (<a href="cplusplus08.html#EXCEPTIONS">8</a>) a
section was added covering the standard exceptions and their meanings; in the
chapter covering static members (<a href="cplusplus10.html#StaticDataFun">10</a>) a section was added
discussing <code>static const</code> data members; and the final chapter
(<a href="cplusplus20.html#CONCRETE">20</a>) covers configurable template classes using <em>local context
structs</em> (replacing the previous <code>ForEach, UnaryPredicate</code> and
<code>BinaryPredicate</code> classes). Furthermore, the final section (covering a
<strong>C++</strong> parser generator) now uses <strong>bisonc++</strong>, rather than the old
(and somewhat outdated) <strong>bison++</strong> program.
    <li> Version 6.1.0 was released shortly after releasing 6.0.0. Following
suggestions received from <a href="mailto:LEOR@winmain.rutgers.edu"><em>Leo Razoumov</em></a> and
Paulo Tribolet, and after receiving many, many useful suggestions and
extensive help from Leo, navigatable <code>.pdf</code> files are from now on
distributed with the <strong>C++</strong> Annotations. Also, some sections were slightly
adapted. 
    <li> Version 6.0.0 was released after a full update of the text, removing
many inconsistencies and typos. Since the update effected the Annotation's
full text an upgrade to a new major version seemed appropriate.  Several new
sections were added: overloading binary operators (section
<a href="cplusplus09.html#OVERLOADBINARY">9.6</a>); throwing exceptions in constructors and destructors
(section <a href="cplusplus08.html#CONSEXCEPTIONS">8.8</a>); function <code>try</code>-blocks (section <a href="cplusplus08.html#FUNTRY">8.9</a>);
calling conventions of static and global functions (section
<a href="cplusplus10.html#CALLINGCONVENTION">10.2.1</a>) and virtual constructors (section <a href="cplusplus14.html#VIRTCONS">14.10</a>). The
chapter on templates was completely rewritten and split into two separate
chapters: chapter <a href="cplusplus18.html#TEMPLATES">18</a> discusses the syntax and use of template
<em>functions</em>; chapter <a href="cplusplus19.html#TEMPCLASS">19</a> discusses template <em>classes</em>. Various
concrete examples were modified; new examples were included as well (chapter
<a href="cplusplus20.html#CONCRETE">20</a>).
    <li> In version 5.2.4 the description of the <em>random_shuffle</em> generic
algorithm (section <a href="cplusplus17.html#SHUFFLE">17.4.39</a>) was modified.
    <li> In version 5.2.3 section <a href="cplusplus02.html#LOCALVARS">2.5.10</a> on local variables was
extended and section <a href="cplusplus02.html#FunctionOverloading">2.5.11</a> on function overloading was
modified by explicitly discussing the effects of the <strong>const</strong> modifier with
overloaded functions. Also, the description of the <code>compare()</code> function in
chapter <a href="cplusplus04.html#String">4</a> contained an error, which was repaired.
    <li> In version 5.2.2 a leftover in section <a href="cplusplus09.html#EXPLICIT">9.4</a>
from a former version was removed and the corresponding text was
updated. Also, some minor typos were corrected.
    <li> In version 5.2.1 various typos were repaired, and some paragraphs
were further clarified. Furthermore, a section was added to the <em>template</em>
chapter (chapter <a href="cplusplus18.html#TEMPLATES">18</a>), about creating several <code>iterator</code>
types. This topic was further elaborated in chapter <a href="cplusplus20.html#CONCRETE">20</a>, where the
section about the construction of a reverse iterator (section
<a href="cplusplus20.html#CONCRETEITER">20.5</a>) was completely rewritten.  In the same chapter, a
<a name="an9"></a>
<em>universal text to anything convertor</em> is discussed (section <a href="cplusplus20.html#A2X">20.6</a>).
    Also, <code>LaTeX</code>, <code>PostScript</code> and <code>PDF</code> versions fitting the
<a name="an10"></a>
<em>US-letter</em>
    <a name="an11"></a>
 paper size are now available as
<a name="an12"></a>
 <code>cplusplus</code><strong>us</strong> versions: <code>cplusplusus.latex,
cplusplusus.ps</code> and <code>cplusplus.pdf</code>. The <em>A4-paper</em> size is of course
kept, and remains to be available in the <code>cplusplus.latex, cplusplus.ps</code> and
<code>cpluspl.pdf</code> files.
    
    <li> Version 5.2.0 was released after adding a section about
the
<code>mutable</code> keyword (section <a href="cplusplus06.html#MUTABLE">6.5</a>), and after thoroughly changing the
discussion of the <code>Fork()</code> abstract base class (section <a href="cplusplus20.html#FORK">20.3</a>). All
examples should now be up-to-date with respect to the use of the <code>std</code>
namespace.
    <li> However, in the meantime the <a name="an13"></a>
Gnu
            <a name="an14"></a>
<code>g++</code> <a name="an15"></a>
compiler version 3.2 was <a name="an16"></a>

released&nbsp;(<a target=_top href="http://www.gnu.org">http://www.gnu.org</a>). In this version extensions to
the
        <a name="an17"></a>
abstract containers (see chapter <a href="cplusplus12.html#Containers">12</a>) like the
        <a name="an18"></a>
hash_map (see section <a href="cplusplus12.html#HASHMAP">12.3.11</a>) were placed in a separate
namespace, <a name="an19"></a>
<code>__gnu_cxx</code>. This namespace should be used when using these
containers. However, this may break compilations of sources with <code>g++</code>,
version 3.0. In that case, a compilation can be performed conditionally to
the 3.2 and the 3.0 compiler version, defining <code>__gnu_cxx</code> for the 3.2
version. Alternatively, the <a name="an20"></a>
<em>dirty trick</em>
        <pre>
    #define __gnu_cxx std
</pre>
    can be placed just before header files in which the <code>__gnu_cxx</code>
namespace is used. This might eventually result in name-collisions, and it's a
dirty trick by any standards, so please don't tell anybody I wrote this down.
    <li> Version 5.1.1 was released after modifying the sections related to
the <a name="an21"></a>
<code>fork()</code> <a name="an22"></a>
system call in chapter <a href="cplusplus20.html#CONCRETE">20</a>. Under the <a name="an23"></a>
ANSI/ISO
standard many of the previously available extensions (like <a name="an24"></a>
<code>procbuf</code>, and
<a name="an25"></a>
<code>vform()</code>) applied to streams were discontinued. Starting with version
5.1.1. ways of constructing these facilities under the ANSI/ISO standard are
discussed in the <strong>C++</strong> Annotations. I consider the involved subject
sufficiently complex to warrant the upgrade to a new subversion.
    <li> With the advent of the <a name="an26"></a>
Gnu <a name="an27"></a>
<code>g++</code> compiler version 3.00, a more
strict implementation of the <a name="an28"></a>
ANSI/ISO <strong>C++</strong> standard became
available. This resulted in version 5.1.0 of the Annotations, appearing
shortly after version 5.0.0. In version 5.1.0 chapter <a href="cplusplus05.html#IOStreams">5</a> was
modified and several cosmetic changes took place (e.g., removing <code>class</code>
from template type parameter lists, see chapter <a href="cplusplus18.html#TEMPLATES">18</a>). Intermediate
versions (like 5.0.0a, 5.0.0b) were not further documented, but were mere
intermediate releases while approaching version 5.1.0. Code
examples will gradually be adapted to the new release of the compiler.
    <blockquote><strong>
        In the meantime the reader should be prepared to insert
        <a name="an29"></a>
</strong>
<p>
<pre>
        using namespace std;
</pre>
<p>
<strong>in many code examples, just beyond the <a name="an30"></a>
<code>#include</code>
        <a name="an31"></a>
preprocessor directives as a temporary measure to make the
    example accepted by the compiler.</strong>
    </blockquote>
    <li> New insights develop all the time, resulting in version 5.0.0 of the
Annotations. In this version a lot of old code was cleaned up and typos were
repaired. According to current standard, <em>namespaces</em> are required in
<strong>C++</strong> programs, so they are introduced now very early (in section
<a href="cplusplus02.html#INTRONAME">2.5.1</a>) in the Annotations. A new section about using external
programs was added to the Annotations (and removed again in version 5.1.0),
and the new <a name="an32"></a>
<code>stringstream</code> class, replacing the <a name="an33"></a>
<code>strstream</code> class is now
covered too (sections <a href="cplusplus05.html#OSTRINGSTREAM">5.4.3</a> and <a href="cplusplus05.html#ISTRINGSTREAM">5.5.3</a>). Actually,
the chapter on input and output was completely rewritten. Furthermore, the
operators <code>new</code> and <code>delete</code> are now discussed in chapter <a href="cplusplus07.html#MEMORY">7</a>,
where they fit better than in a chapter on classes, where they previously were
discussed. Chapters were moved, split and reordered, so that subjects could
generally be introduced without forward references. Finally, the <a name="an34"></a>
<code>html</code>,
<a name="an35"></a>
PostScript and <a name="an36"></a>
pdf versions of the <strong>C++</strong> Annotations now contain an
index (<a name="an37"></a>
sigh of relief ?)  All in, considering the volume and nature of the
modifications, it seemed right to upgrade to a full major version. So here it
is.
<p>
Considering the volume of the Annotations, I'm sure there will be
typos found every now and then. Please do not hesitate to send me mail
containing any mistakes you find or corrections you would like to suggest.
    <li> In release <code>4.4.1b</code> the pagesize in the LaTeX file was defined to
be <code>din A4</code>. In countries where other pagesizes are standard the default
pagesize might be a better choice. In that case, remove the
<code>a4paper,twoside</code> option from <code>cplusplus.tex</code> (or <code>cplusplus.yo</code> if you
have <code>yodl</code> installed), and reconstruct the Annotations from the
<em>TeX</em>-file or <code>Yodl</code>-files.
<p>
The Annotations mailing lists was stopped at release <code>4.4.1d</code>. From this
point on only minor modifications were expected, which are not anymore
generally announced.
<p>
At some point, I considered version <code>4.4.1</code> to be the final version of the
<strong>C++</strong> Annotations. However, a section on special I/O functions was added to
cover unformatted I/O, and the section about the <code>string</code> datatype had its
layout improved and was, due to its volume, given a chapter of its own
(chapter <a href="cplusplus04.html#String">4</a>). All this eventually resulted in version <code>4.4.2</code>.
<p>
Version <code>4.4.1</code> again contains new material, and reflects the
    <a name="an38"></a>

<a href="ftp://research.att.com/dist/c++std/WP/">ANSI/ISO</a> standard (well, I try to
have it reflect the <a name="an39"></a>
ANSI/ISO standard). In version 4.4.1. several new
sections and chapters were added, among which a chapter about the
    <a name="an40"></a>
<em>Standard Template Library</em> (<a name="an41"></a>
STL) and <a name="an42"></a>
<em>generic algorithms</em>.
<p>
Version <code>4.4.0</code> (and subletters) was a mere construction version and was
never made available.
<p>
The version <code>4.3.1a</code> is a precursor of <code>4.3.2</code>. In <code>4.3.1a</code> most of the
typos I've received since the last update have been processed. In version
<code>4.3.2</code> extra attention was paid to the syntax for <a name="an43"></a>

function addresses and <a name="an44"></a>
pointers to member functions.
<p>
The decision to upgrade from version 4.2.* to 4.3.* was made after realizing
that the lexical scanner function <code>yylex()</code> can be defined in the
scanner class that is derived from <code>yyFlexLexer</code>. Under this approach
the <code>yylex()</code> function can access the members of the class derived from
<code>yyFlexLexer</code> as well as the public and protected members of
<code>yyFlexLexer</code>. The result of all this is a clean implementation of the rules
defined in the <code>flex++</code> specification file.
<p>
The upgrade from version 4.1.* to 4.2.* was the result of the inclusion of
section <a href="cplusplus03.html#BOOL">3.3.1</a> about the <strong>bool</strong> data type in chapter
<a href="cplusplus03.html#FirstImpression">3</a>. The distinction between differences between <strong>C</strong> and
<strong>C++</strong> and extensions of the <strong>C</strong> programming languages is (albeit a bit
fuzzy) reflected in the introduction chapter and the chapter on first
impressions of <strong>C++</strong>: The <a href="cplusplus02.html#IntroC">introduction chapter</a>
covers some differences between <strong>C</strong> and <strong>C++</strong>, whereas the chapter about
<a href="cplusplus03.html#FirstImpression">first impressions</a> of <strong>C++</strong> covers some extensions of
the <strong>C</strong> programming language as found in <strong>C++</strong>.
<p>
Major version 4 is a major rewrite of the previous
version 3.4.14. The document was rewritten from SGML to
Yodl and many
new sections were added. All sections got a tune-up. The distribution basis,
however, hasn't changed: see <a href="cplusplus02.html#IntroC">the introduction</a>.
<p>
Modifications in versions 1.*.*, 2.*.*, and 3.*.* (replace the stars by any
applicable number) were not logged.
<p>
Subreleases like <code>4.4.2a</code> etc. contain bugfixes and typographical
corrections.
    </ul>
<p>
<a name="l4"></a>
<h2>2.2: C++'s history</h2>
    <a name="intro/history"></a>The first implementation of <strong>C++</strong> was developed in the nineteen-eighties at
the AT&amp;T Bell Labs, where the Unix operating system was created.
<p>
<strong>C++</strong> was originally a `pre-compiler', similar to the preprocessor of
<strong>C</strong>, which converted special constructions in its source code to plain
<strong>C</strong>. This code was then compiled by a normal <strong>C</strong> compiler. The
`pre-code', which was read by the <strong>C++</strong> pre-compiler, was usually located
in a file with the extension <code>.cc</code>, <code>.C</code> or <code>.cpp</code>. This file
would then be converted to a C source file with the extension <code>.c</code>, which
was compiled and linked.
<p>
The nomenclature of <strong>C++</strong> source files remains: the extensions <code>.cc</code> and
<code>.cpp</code> are still used. However, the preliminary work of a <strong>C++</strong>
pre-compiler is in modern compilers usually included in the actual compilation
process. Often compilers will determine the type of a source file by its
extension. This holds true for Borland's and Microsoft's <strong>C++</strong> compilers,
which assume a <strong>C++</strong> source for an extension <code>.cpp</code>. The <a name="an45"></a>
Gnu
<a name="an46"></a>
compiler <a name="an47"></a>
<code>g++</code>, which is available on many Unix platforms, assumes for
<strong>C++</strong> the extension <code>.cc</code>.
<p>
The fact that <strong>C++</strong> used to be compiled into <strong>C</strong> code is also visible
from the fact that <strong>C++</strong> is a superset of <strong>C</strong>: <strong>C++</strong> offers the full
<strong>C</strong> grammar and supports all <strong>C</strong>-library functions, and adds to this
features of its own. This makes the transition from <strong>C</strong> to
<strong>C++</strong> quite easy. Programmers familiar with <strong>C</strong> may start
`programming in <strong>C++</strong>' by using source files having extensions <code>.cc</code> or
<code>.cpp</code> instead of <code>.c</code>, and may then comfortably slip into all the
possibilities offered by <strong>C++</strong>. No abrupt change of habits is required.
<p>
<a name="l5"></a>
<h3>2.2.1: History of the C++ Annotations</h3>
        <a name="intro/annohistory"></a>The original version of the <strong>C++</strong> Annotations was written by Frank Brokken
and Karel Kubat in Dutch using <code>LaTeX</code>. After some time, Karel rewrote the
text and converted the guide to a more suitable format and (of course) to
English in september 1994.
<p>
The first version of the guide appeared on the net in october 1994. By then it
was converted to <code>SGML</code>.
<p>
Gradually new chapters were added, and the contents were modified and further
improved (thanks to countless readers who sent us their comment).
<p>
The transition from major version three to major version four was realized by
Frank: again new chapters were added, and the source-document was converted
from <code>SGML</code> to <a target=_top href="http://yodl.sourceforge.net">yodl</a>.
    <blockquote>
    The <strong>C++</strong> Annotations are freely distributable. Be sure to read
    the <a href="legal.shtml">legal notes</a>.
<p>
<strong>Reading the annotations beyond this point implies that you are aware of
    these notes and that you agree with them.</strong>
    </blockquote>
    If you like this document, tell your friends about it. Even better, let us
know by sending email to <a href="mailto:f.b.brokken@rug.nl">Frank</a>.
<p>
In the <a name="an48"></a>
Internet, many useful <a name="an49"></a>
hyperlinks exist to <strong>C++</strong>. Without even
suggesting completeness (and without being checked regularly for existence:
they might have died by the time you read this), the following might be
worthwhile visiting:
    <ul>
    <li> <a name="an50"></a>

        <a target=_top href="http://www.cplusplus.com/ref/">http://www.cplusplus.com/ref/</a>: a reference site for <strong>C++</strong>.
<p>
<li> <a name="an51"></a>

        <a target=_top href="http://www.csci.csusb.edu/dick/c++std/cd2/index.html">http://www.csci.csusb.edu/dick/c++std/cd2/index.html</a>:
        offers a version
        of the 1996 working paper of the <strong>C++</strong> <a name="an52"></a>
ANSI/ISO standard.
    </ul>
<p>
<a name="CppComp"></a><a name="l6"></a>
<h3>2.2.2: Compiling a C program using a C++ compiler</h3>
        <a name="intro/cascpp"></a>    For the sake of completeness, it must be mentioned here that <strong>C++</strong> is
`almost' a superset of <strong>C</strong>. There are some differences you might encounter
when you simply rename a file to a file having the extension <code>.cc</code> and run
it through a <strong>C++</strong> compiler:
    <ul>
    <li> In <strong>C</strong>, <a name="an53"></a>
<code>sizeof</code><code>('c')</code> equals <code>sizeof(int)</code>, <code>'c'</code> being
any ASCII character.  The underlying philosophy is probably that <code>char</code>s,
when passed as arguments to functions, are passed as integers
anyway. Furthermore, the <strong>C</strong> compiler handles a character constant like
<code>'c'</code> as an integer constant. Hence, in <strong>C</strong>, the function calls
        <pre>
    putchar(10);
</pre>
    and
        <pre>
    putchar('\n');
</pre>
    are synonyms.
<p>
In contrast, in <strong>C++</strong>, <code>sizeof('c')</code> is always 1 (but see also section
<a href="cplusplus03.html#WCHAR">3.3.2</a>), while an <code>int</code> is still an <code>int</code>. As we shall see later (see
section <a href="cplusplus02.html#FunctionOverloading">2.5.11</a>), the two function calls
        <pre>
    somefunc(10);
</pre>
    and
        <pre>
    somefunc('\n');
</pre>
    may be handled by quite separate functions: <strong>C++</strong> distinguishes
functions not only by their names, but also by their argument types, which are
different in these two calls: one call using an <code>int</code> argument, the other
one using a <code>char</code>.
    <li> <strong>C++</strong> requires very strict <a name="an54"></a>
prototyping of external
functions. E.g., a prototype like
        <pre>
    extern void func();
</pre>
    in <strong>C</strong> means that a function <code>func()</code> exists, which returns no
value. The declaration doesn't specify which arguments (if any) the function
takes.
<p>
In contrast, such a declaration in <strong>C++</strong> means that the function
<code>func()</code> takes no arguments at all: passing arguments to it results in a
compile-time error.
    </ul>
<p>
<a name="COMPILATION"></a><a name="l7"></a>
<h3>2.2.3: Compiling a C++ program</h3>
        <a name="intro/compiling"></a>To compile a <strong>C++</strong> program, a <strong>C++</strong> <a name="an55"></a>
compiler is
needed. Considering the free nature of this document, it won't come as a
surprise that a <a name="an56"></a>
<em>free compiler</em> is suggested here. The
    <a name="an57"></a>
Free Software Foundation (<a name="an58"></a>
FSF) provides at <a name="an59"></a>

    <a target=_top href="http://www.gnu.org">http://www.gnu.org</a> a free <strong>C++</strong>
compiler which is, among other places, also part of the <a name="an60"></a>
Debian
    <a name="an61"></a>

    (<a target=_top href="http://www.debian.org">http://www.debian.org</a>) distribution of <a name="an62"></a>
Linux
    (<a name="an63"></a>
 <a target=_top href="http://www.linux.org">http://www.linux.org</a>).
<p>
<a name="l8"></a>
<strong>2.2.3.1: C++ under MS-Windows</strong>
            <a name="intro/mswindows"></a>For <a name="an64"></a>
MS-Windows <a name="an65"></a>
Cygnus <a name="an66"></a>

(<a target=_top href="http://sources.redhat.com/cygwin">http://sources.redhat.com/cygwin</a>) provides the foundation
for installing the <em>Windows port</em> of the <a name="an67"></a>
Gnu <a name="an68"></a>
<code>g++</code> <a name="an69"></a>
compiler.
<p>
When visiting the above URL to obtain a <a name="an70"></a>
 free <code>g++</code>
compiler, click on <code>install now</code>. This will download the file <a name="an71"></a>
<code>setup.exe</code>,
which can be run to install <code>cygwin</code>. The software to be installed can be
downloaded by <code>setup.exe</code> from the internet. There are alternatives (e.g.,
using a CD-ROM), which are described on the <a name="an72"></a>
Cygwin page. Installation
proceeds interactively. The offered defaults are normally what you would want.
<p>
The most recent Gnu <code>g++</code> compiler can be obtained from
    <a name="an73"></a>
 <a target=_top href="http://gcc.gnu.org">http://gcc.gnu.org</a>. If the compiler that is
made available in the Cygnus distribution lags behind the latest version, the
sources of the latest version can be downloaded after which the compiler can
be built using an already available compiler. The compiler's webpage
(mentioned above) contains detailed instructions on how to proceed. In our
experience building a new compiler within the Cygnus environment works
flawlessly.
<p>
<a name="l9"></a>
<strong>2.2.3.2: Compiling a C++ source text</strong>
            <a name="intro/compilesources"></a>In general, the following command is used to compile a <strong>C++</strong> source file
`<code>source.cc</code>':
        <pre>
        g++ source.cc
</pre>
    This produces a binary program (<code>a.out</code> or <code>a.exe</code>). If the default
name is not wanted, the name of the executable can be specified using the
<code>-o</code> flag (here producing the program <code>source</code>):
        <pre>
        g++ -o source source.cc
</pre>
    If a mere compilation is required, the compiled module can be generated
using the <code>-c</code> flag:
        <pre>
        g++ -c source.cc
</pre>
    This produces the file <code>source.o</code>, which can be linked to other modules
later on.
<p>
Using the <a name="an74"></a>
 
    <a target=_top href="ftp://ftp.rug.nl/contrib/frank/software/linux/icmake">icmake</a>
    program a maintenance script can be used to assist in the construction and
maintenance of <strong>C++</strong> programs. A generic <code>icmake</code> maintenance script
(<a name="an75"></a>
<code>icmbuild</code>) is available as well. Alternatively, the standard <a name="an76"></a>
<code>make</code>
program can be used to maintain <strong>C++</strong> programs. It is strongly advised to
start using maintenance scripts or programs early in the study of the <strong>C++</strong>
programming language. Alternative approaches were implemented by former
students, e.g., <a target=_top href="http://nl.logilogi.org/MetaLogi/LaKe">lake</a> by Wybo
Wiersma and <a target=_top href="http://ccbuild.sourceforge.net/">ccbuild</a> by Bram Neijt.
<p>
<a name="Pretensions"></a><a name="l10"></a>
<h2>2.3: C++: advantages and claims</h2>
    <a name="intro/advantage"></a>Often it is said that programming in <strong>C++</strong> leads to `better' programs. Some
of the claimed advantages of <strong>C++</strong> are:
    <ul>
    <li> New programs would be developed in less time because old code can be
reused.
    <li> Creating and using new data types would be easier than in <strong>C</strong>.
    <li> The memory management under <strong>C++</strong> would be easier and more
transparent.
    <li> Programs would be less bug-prone, as <strong>C++</strong> uses a stricter syntax
and type checking.
    <li> <a name="an77"></a>
`Data hiding', the usage of data by one program part
while other program parts cannot access the data, would be easier to implement
with <strong>C++</strong>.
    </ul>
    Which of these allegations are true? Originally, our impression was that
the <strong>C++</strong> language was a little overrated; the same holding true for the
entire object-oriented programming (OOP) approach. The enthusiasm for the
<strong>C++</strong> language resembles the once uttered allegations about
Artificial-Intelligence (AI) languages like <a name="an78"></a>
Lisp and <a name="an79"></a>
Prolog: these
languages were supposed to solve the most difficult AI-problems `almost
without effort'. Obviously, too promising stories about any programming
language must be overdone; in the end, each problem can be coded in any
programming language (say <a name="an80"></a>
BASIC or <a name="an81"></a>
assembly language).  The advantages
or disadvantages of a given programming language aren't in `what you can do
with them', but rather in `which tools the language offers to implement an
efficient and understandable solution for a programming problem'.
<p>
Concerning the above allegations of <strong>C++</strong>, we support the following, however.
    <ul>
    <li> The development of new programs while existing code is reused
can also be realized in <strong>C</strong> by, e.g., using function libraries.
Functions can be collected in a library and need not be re-invented with each
new program. <strong>C++</strong>, however, offers specific syntax possibilities for
code reuse, apart from function libraries (see chapter <a href="cplusplus13.html#INHERITANCE">13</a>).
    <li> Creating and using new data types is also very well possible in
<strong>C</strong>; e.g., by using <code>struct</code>s, <code>typedef</code>s etc.. From these types other
types can be derived, thus leading to <code>struct</code>s containing <code>struct</code>s and
so on. In <strong>C++</strong> these facilities are augmented by defining data types which
are completely `self supporting', taking care of, e.g., their memory
management automatically (without having to resort to an independently
operating memory management system as used in, e.g., <strong>Java</strong>).
    <li> Memory management is in principle in <strong>C++</strong> as easy or as difficult
as in <strong>C</strong>. Especially when dedicated <strong>C</strong> functions such as <code>xmalloc()</code>
and <code>xrealloc()</code> are used (allocating the memory or aborting the program
when the memory pool is exhausted). However, with <code>malloc()</code> like functions
it is easy to err: miscalculating the required number of bytes in a
<code>malloc()</code> call is a frequently occurring error. Instead, <strong>C++</strong> offers
facilities for allocating memory in a somewhat safer way, through its
<code>operator new</code>.
    <li> Concerning `bug proneness' we can say that <strong>C++</strong> indeed uses
stricter type checking than <strong>C</strong>. However, most modern <strong>C</strong> compilers
implement `warning levels'; it is then the programmer's choice to disregard or
heed a generated warning. In <strong>C++</strong> many of such warnings become fatal errors
(the compilation stops).
    <li> As far as `data hiding' is concerned, <strong>C</strong> does offer some tools.
E.g., where possible, local or <a name="an82"></a>
<code>static</code> variables can be used and special
data types such as <code>struct</code>s can be manipulated by dedicated functions.
Using such techniques, data hiding can be realized even in <strong>C</strong>; though it
must be admitted that <strong>C++</strong> offers special syntactical constructions, making
it far easier to realize `data hiding' in <strong>C++</strong> than in <strong>C</strong>.
    </ul>
    <strong>C++</strong> in particular (and OOP in general) is of course not <em>the</em>
solution to all programming problems. However, the language <em>does</em> offer
various new and elegant facilities which are worthwhile investigating. At the
same time, the level of grammatical complexity of <strong>C++</strong> has increased
significantly compared to <strong>C</strong>. This may be considered a serious disadvantage
of the language. Although we got used to this increased level of complexity
over time, the transition wasn't fast or painless. With the <strong>C++</strong> Annotations we
hope to help the reader to make the transition from <strong>C</strong> to <strong>C++</strong> by
providing, indeed, our <em>annotations</em> to what is found in some textbooks on
<strong>C++</strong>. It is our hope that you like this document and may benefit from it.
Enjoy and good luck on your journey into <strong>C++</strong>!
<p>
<a name="OOP"></a><a name="l11"></a>
<h2>2.4: What is Object-Oriented Programming?</h2>
    <a name="intro/object"></a>Object-oriented (and object-based) programming propagates a slightly different
approach to programming problems than the strategy usually used in <strong>C</strong>
programs. In <strong>C</strong> programming problems are usually solved using a
`<a name="an83"></a>
procedural approach': a problem is decomposed into subproblems and this
process is repeated until the subtasks can be coded. Thus a conglomerate of
functions is created, communicating through arguments and variables, global or
local (or <code>static</code>).
<p>
In contrast (or maybe better: in addition) to this, an object-based approach
identifies <strong>keywords</strong> in a problem. These keywords are then depicted
in a diagram and arrows are drawn between these keywords to define an internal
hierarchy. The keywords will be the objects in the implementation and the
hierarchy defines the relationship between these objects. The term object is
used here to describe a limited, well-defined structure, containing all
information about an entity: data types and functions to manipulate the
data. As an example of an <a name="an84"></a>
object oriented approach, an illustration
follows:
    <blockquote>
    The employees and owner of a car dealer and auto garage company are paid
    as follows. First, mechanics who work in the garage are paid a certain sum
    each month. Second, the owner of the company receives a fixed amount each
    month. Third, there are car salesmen who work in the showroom and receive
    their salary each month plus a bonus per sold car. Finally, the company
    employs second-hand car purchasers who travel around; these employees
    receive their monthly salary, a bonus per bought car, and a restitution of
    their travel expenses.
    </blockquote>
    When representing the above salary administration, the keywords could be
mechanics, owner, salesmen and purchasers. The properties of such units are: a
monthly salary, sometimes a bonus per purchase or sale, and sometimes
restitution of travel expenses. When analyzing the problem in this manner we
arrive at the following representation:
    <ul>
    <li> The owner and the mechanics can be represented as the same type,
receiving a given salary per month. The relevant information for such a type
would be the monthly amount. In addition this object could contain data as the
name, address and social security number.
    <li> Car salesmen who work in the showroom can be represented as the same
type as above but with some <em>extra</em> functionality: the number of
transactions (sales) and the bonus per transaction.
<p>
In the hierarchy of objects we would define the dependency between the
first two objects by letting the car salesmen be `derived' from
the owner and mechanics.
    <li> Finally, there are the second-hand car purchasers. These share the
functionality of the salesmen except for the travel expenses. The additional
functionality would therefore consist of the expenses made and this type would
be derived from the salesmen.
    </ul>
    The hierarchy of the thus identified objects are further illustrated in
Figure <a href="cplusplus02.html#objects">1</a>.
    <a name="objects"></a><p><center><img src="intro/objects.gif" align="bottom" alt="Figure 1 is shown here."/><br>
Figure 1: Hierarchy of objects in the salary administration.
</center><p><br>

<p>
The overall process in the definition of a hierarchy such as the above starts
with the description of the most simple type. Subsequently more complex types
are derived, while each derivation adds a little functionality. From these
derived types, more complex types can be derived <em>ad infinitum</em>, until a
representation of the entire problem can be made.
<p>
In <strong>C++</strong> each of the objects can be represented in a
<a href="cplusplus06.html#Classes"><em>class</em></a>, containing the necessary functionality to do useful
things with the variables (called <em>objects</em>) of these classes. Not all of
the functionality and not all of the properties of a class are usually
available to objects of other classes. As we will see, classes tend to
<em>hide</em> their properties in such a way that they are not directly modifiable
by the outside world. Instead, dedicated functions are used to reach or modify
the properties of objects. Also, these objects tend to be
<em>self-contained</em>. They <em>encapsulate</em> all the functionality and data
required to perform their tasks and to uphold the object's integrity.
<p>
<a name="l12"></a>
<h2>2.5: Differences between C and C++</h2>
    <a name="intro/differences"></a>In this section some examples of <strong>C++</strong> code are shown. Some differences
between <strong>C</strong> and <strong>C++</strong> are highlighted.
<p>
<a name="INTRONAME"></a><a name="l13"></a>
<h3>2.5.1: Namespaces</h3>
        <a name="intro/namespaces"></a><strong>C++</strong> introduces the notion of a <a name="an85"></a>
<em>namespace</em>: all symbols are defined
in a larger context, called a <em>namespace</em>. Namespaces are used to avoid
    <a name="an86"></a>
name conflicts that could arise when a programmer would like to define
a function like <a name="an87"></a>
<code>sin()</code> operating on <em>degrees</em>, but does not want to lose
the capability of using the standard <code>sin()</code> function, operating on
<em>radians</em>.
<p>
Namespaces are covered extensively in section <a href="cplusplus03.html#Namespaces">3.7</a>. For now it
should be noted that most compilers require the explicit declaration of a
<a name="an88"></a>
<em>standard namespace</em>: <a name="an89"></a>
<code>std</code>. So, unless otherwise indicated, it is
stressed that all examples in the Annotations now implicitly use the
    <a name="an90"></a>

        <pre>
        using namespace std;
</pre>
    declaration. So, if you actually intend to compile the examples given in
the Annotations, make sure that the sources start with the above <code>using</code>
declaration.
<p>
<a name="l14"></a>
<h3>2.5.2: End-of-line comment</h3>
        <a name="intro/eoln"></a>According to the ANSI definition, `<a name="an91"></a>
end of line comment' is implemented in
the syntax of <strong>C++</strong>. This comment starts with <a name="an92"></a>
<code>//</code> and ends with the
end-of-line marker. The standard <strong>C</strong> comment, delimited by <code>/*</code> and <code>*/</code>
can still be used in <strong>C++</strong>:
        <pre>
    int main()
    {
        // this is end-of-line comment
        // one comment per line

        /*
            this is standard-C comment, covering
            multiple lines
        */
    }
</pre>
    Despite the example, it is advised <em>not</em> to use <strong>C</strong> type comment
inside the body of <strong>C++</strong> functions. At times you will temporarily want to
suppress sections of existing code. In those cases it's very practical to be
able to use standard <strong>C</strong> comment. If such suppressed code itself contains
such comment, it would result in nested comment-lines, resulting in compiler
errors. Therefore, the <a name="an93"></a>
rule of thumb is not to use <strong>C</strong> type comment
inside the body of <strong>C++</strong> functions.
<p>
<a name="l15"></a>
<h3>2.5.3: NULL-pointers vs. 0-pointers</h3>
        <a name="intro/null"></a>In <strong>C++</strong> all zero values are coded as <code>0</code>. In <strong>C</strong>, where pointers are
concerned, <a name="an94"></a>
<code>NULL</code> is often used. This difference is purely stylistic, though
one that is widely adopted. In <strong>C++</strong> there's no need anymore to use
<code>NULL</code>, and using <code>0</code> is actually preferred when indicating null-pointer
values.
<p>
<a name="l16"></a>
<h3>2.5.4: Strict type checking</h3>
        <a name="intro/type"></a><strong>C++</strong> uses very strict <a name="an95"></a>
type checking. A prototype must be known for each
function before it is called, and the call must match the prototype.
The program
        <pre>
    int main()
    {
        printf("Hello World\n");
    }
</pre>
    does often compile under <strong>C</strong>, though with a warning that <a name="an96"></a>
<code>printf()</code> is
not a known function. Many <strong>C++</strong> compilers will fail to produce code in such
a situation. The error is of course the missing <a name="an97"></a>
<code>#include &lt;stdio.h&gt;</code>
directive.
<p>
Although, while we're at it: in <strong>C++</strong> the function <a name="an98"></a>
<code>main()</code> <em>always</em>
uses the <code>int</code> <a name="an99"></a>
return value. It is possible to define <a name="an100"></a>
<code>int main()</code>
without an <a name="an101"></a>
explicit return statement, but a <a name="an102"></a>
<code>return</code> statement without an
expression cannot be given inside the <code>main()</code> function: a <code>return</code>
statement in <code>main()</code> must always be given an <code>int</code>-expression. For
example:
        <pre>
    int main()
    {
        return;     // won't compile: expects int expression
    }
</pre>
<p>
<a name="CPPCASTS"></a><a name="l17"></a>
<h3>2.5.5: A new syntax for casts</h3>
        <a name="intro/cast"></a>Traditionally, <strong>C</strong> offers the following <em>cast</em> construction:
                         <pre>
        (typename)expression
</pre>
 in which <code>typename</code> is
the name of a valid <em>type</em>, and <code>expression</code> an expression. Apart from the
<strong>C</strong> style cast (now deprecated) <strong>C++</strong> also supports the <em>function call</em>
notation:
                    <pre>
        typename(expression)
</pre>
 This function call notation is
not actually a cast, but the request to the compiler to construct an
(anonymous) variable of type <code>typename</code> from the expression
<code>expression</code>. This form is actually very often used in <strong>C++</strong>, but should
<em>not</em> be used for casting.  Instead, four <a name="an103"></a>
<em>new-style casts</em> were
introduced:
    <ul>
    <li> The standard cast to convert one type to another is
                     <pre>
        static_cast&lt;type&gt;(expression)
</pre>
    <li> There is a special cast to do away with the <code>const</code>
type-modification:
                     <pre>
        const_cast&lt;type&gt;(expression)
</pre>
    <li> A third cast is used to change the <em>interpretation</em> of information:
                   <pre>
        reinterpret_cast&lt;type&gt;(expression)
</pre>
    <li> And, finally, there is a cast form which is used in combination with
polymorphism (see chapter <a href="cplusplus14.html#POLYMORPHISM">14</a>). The
                    <pre>
        dynamic_cast&lt;type&gt;(expression)
</pre>
    is performed run-time to convert, e.g., a pointer to an object of a
certain class to a pointer to an object further down its so-called <em>class
hierarchy</em>. At this point in the <em>Annotations</em> it is a bit premature to
discuss the <code>dynamic_cast</code>, but we will return to this topic in section
<a href="cplusplus14.html#DYNAMICCAST">14.5.1</a>.
    </ul>
<p>
<a name="l18"></a>
<strong>2.5.5.1: The `static_cast'-operator</strong>
            <a name="intro/staticcast"></a>    The <a name="an104"></a>
<code>static_cast&lt;type&gt;(expression)</code> operator is used to convert one type
to an acceptable other type. E.g., <code>double</code> to <code>int</code>. An example of such a
cast is, assuming <code>d</code> is of type <code>double</code> and <code>a</code> and <code>b</code> are
<code>int</code>-type variables. In that situation, computing the floating point
quotient of <code>a</code> and <code>b</code> requires a cast:
        <pre>
        d = static_cast&lt;double&gt;(a) / b;
</pre>
    If the cast is omitted, the division operator will cut-off the remainder,
as its operands are <code>int</code> expressions. Note that the division should be
placed outside of the cast. If not, the (integer) division will be performed
before the cast has a chance to convert the type of the operand to <code>double</code>.
Another nice example of code in which it is a good idea to use the
<code>static_cast&lt;&gt;()</code>-operator is in situations where the arithmetic assignment
operators are used in mixed-type situations. E.g., consider the following
expression (assume <code>doubleVar</code> is a variable of type <code>double</code>):
        <pre>
        intVar += doubleVar;
</pre>
This statement actually evaluates to:
     <pre>
        intVar = static_cast&lt;int&gt;(static_cast&lt;double&gt;(intVar) + doubleVar);
</pre>
    <code>IntVar</code> is first promoted to a <code>double</code>, and is then added as
<code>double</code> to <code>doubleVar</code>. Next, the sum is cast back to an <code>int</code>.  These
two conversions are a bit overdone. The same result is obtained by explicitly
casting the <code>doubleVar</code> to an <code>int</code>, thus obtaining an <code>int</code>-value for
the right-hand side of the expression:
        <pre>
        intVar += static_cast&lt;int&gt;(doubleVar);
</pre>
<p>
<a name="l19"></a>
<strong>2.5.5.2: The `const_cast'-operator</strong>
            <a name="intro/constcast"></a>    The <a name="an105"></a>
<code>const_cast&lt;type&gt;(expression)</code> operator is used to undo the
<code>const</code>-ness of a (pointer) type. Assume that a function
    <code>fun(char *s)</code> is available, which performs some operation on its
<code>char *s</code> parameter. Furthermore, assume that it's <em>known</em> that the
function does not actually alter the string it receives as its argument. How
can we use the function with a string like <code>char const hello[] = "Hello
world"</code>?
<p>
Passing <code>hello</code> to <code>fun()</code> produces the warning
    <pre>
        passing `const char *' as argument 1 of `fun(char *)' discards const
</pre>
        which can be prevented using the call
                    <pre>
        fun(const_cast&lt;char *&gt;(hello));
</pre>
<p>
<a name="l20"></a>
<strong>2.5.5.3: The `reinterpret_cast'-operator</strong>
            <a name="intro/reinterpretcast"></a>    The <a name="an106"></a>
<code>reinterpret_cast&lt;type&gt;(expression)</code> operator is used to reinterpret
pointers. For example, using a <code>reinterpret_cast&lt;&gt;()</code> the individual
bytes making up a <code>double</code> value can easily be reached. Assume <code>doubleVar</code>
is a variable of type <code>double</code>, then the individual bytes can be reached
using
        <pre>
        reinterpret_cast&lt;char *&gt;(&amp;doubleVar)
</pre>
    This particular example also suggests the danger of the cast: it looks as
though a standard <code>C</code>-string is produced, but there is not normally a
trailing 0-byte. It's just a way to reach the individual bytes of the memory
holding a double value.
<p>
More in general: using the cast-operators is a dangerous habit, as it
suppresses the normal type-checking mechanism of the compiler. It is suggested
to <a name="an107"></a>
prevent casts if at all possible. If circumstances arise in which casts
have to be used, document the reasons for their use well in your code, to make
double sure that the cast will not eventually be the underlying cause for a
program to misbehave.
<p>
<a name="l21"></a>
<strong>2.5.5.4: The `dynamic_cast'-operator</strong>
            <a name="intro/dynamiccast"></a>    The <a name="an108"></a>
<code>dynamic_cast&lt;&gt;()</code> operator is used in the context of
<a name="an109"></a>
polymorphism. Its discussion is postponed until section <a href="cplusplus14.html#DYNAMICCAST">14.5.1</a>.
<p>
<a name="l22"></a>
<h3>2.5.6: The `void' parameter list</h3>
        <a name="intro/void"></a>Within <strong>C</strong>, a function prototype with an <a name="an110"></a>
empty parameter list, such as
        <pre>
    void func();
</pre>
    means that the argument list of the declared function is not
prototyped: the compiler will not warn against improper argument
usage. In <strong>C</strong>, to declare a function having no arguments, the keyword
<a name="an111"></a>
<code>void</code> is used:
        <pre>
    void func(void);
</pre>
    As <strong>C++</strong> enforces strict type checking, an empty parameter list
indicates the absence of any parameter. The keyword <code>void</code> can thus
be omitted: in <strong>C++</strong> the above two function declarations are equivalent.
<p>
<a name="l23"></a>
<h3>2.5.7: The `#define __cplusplus'</h3>
        <a name="intro/cplus"></a>Each <strong>C++</strong> compiler which conforms to the <a name="an112"></a>
ANSI/ISO standard defines the
symbol <a name="an113"></a>
<code>__cplusplus</code>: it is as if each source file were prefixed with the
<a name="an114"></a>
preprocessor directive <a name="an115"></a>
<code>#define __cplusplus</code>.
<p>
We shall see examples of the usage of this symbol in the following sections.
<p>
<a name="l24"></a>
<h3>2.5.8: Using standard C functions</h3>
        <a name="intro/cfunc"></a>Normal <strong>C</strong> functions, e.g., which are compiled and collected in a run-time
library, can also be used in <strong>C++</strong> programs. Such functions, however, must be
declared as <strong>C</strong> functions.
<p>
As an example, the following code fragment declares a function <code>xmalloc()</code>
as a <strong>C</strong> function:
        <pre>
    extern "C" void *xmalloc(size_t size);
</pre>
    This declaration is analogous to a declaration in <strong>C</strong>, except that the
prototype is prefixed with <a name="an116"></a>
<code>extern "C"</code>.
<p>
A slightly different way to declare <strong>C</strong> functions is the following:
        <pre>
    extern "C"
    {
        // C-declarations go in here
    }
</pre>
    It is also possible to place preprocessor directives at the location of
the declarations. E.g., a <strong>C</strong> header file <code>myheader.h</code> which declares
<strong>C</strong> functions can be included in a <strong>C++</strong> source file as follows:
        <pre>
    extern "C"
    {
        #include &lt;myheader.h&gt;
    }
</pre>
    Although these two approaches can be used, they are actually seldomly
encountered in <strong>C++</strong> sources. We will encounter a more frequently used
method to declare external <strong>C</strong> functions in the next section.
<p>
<a name="CHeaders"></a><a name="l25"></a>
<h3>2.5.9: Header files for both C and C++</h3>
        <a name="intro/header"></a>The combination of the predefined symbol <a name="an117"></a>
<code>__cplusplus</code> and of the
possibility to define <a name="an118"></a>
<code>extern "C"</code> functions offers the ability to
create header files for both <strong>C</strong> and <strong>C++</strong>. Such a header file might,
e.g., declare a group of functions which are to be used in both <strong>C</strong> and
<strong>C++</strong> programs.
<p>
The setup of such a header file is as follows:
        <pre>
    #ifdef __cplusplus
    extern "C"
    {
    #endif
        // declaration of C-data and functions are inserted here. E.g.,
        void *xmalloc(size_t size);

    #ifdef __cplusplus
    }
    #endif
</pre>
    Using this setup, a normal <strong>C</strong> header file is enclosed by
    <code>extern "C"</code> <code>{</code> which occurs at the start of the file and by <code>}</code>,
which occurs at the end of the file. The <a name="an119"></a>
<code>#ifdef</code> directives test for the
type of the compilation: <strong>C</strong> or <strong>C++</strong>. The `standard' <strong>C</strong> header files,
such as <a name="an120"></a>
<code>stdio.h</code>, are built in this manner and are therefore usable for
both <strong>C</strong> and <strong>C++</strong>.
<p>
In addition to this, <strong>C++</strong> headers should support <a name="an121"></a>
<em>include guard</em><em>s</em>.
In <strong>C++</strong> it is usually undesirable to include the same header file twice in
the same source file. Such <a name="an122"></a>
multiple inclusions can easily be avoided by
including an <a name="an123"></a>
<code>#ifndef</code> directive in the header file.  For example:
        <pre>
    #ifndef _MYHEADER_H_
    #define _MYHEADER_H_
        // declarations of the header file is inserted here,
        // using #ifdef __cplusplus etc. directives
    #endif
</pre>
    When this file is scanned for the first time by the preprocessor, the
symbol <code>_MYHEADER_H_</code> is not yet defined. The <code>#ifndef</code> condition
succeeds and all declarations are scanned. In addition, the symbol
<code>_MYHEADER_H_</code> is defined.
<p>
When this file is scanned for a second time during the same compilation,
the symbol <code>_MYHEADER_H_</code> has been defined and consequently all information
between the <code>#ifndef</code> and <code>#endif</code> directives is skipped by the compiler.
<p>
In this context the symbol name <code>_MYHEADER_H_</code> serves only for
recognition purposes. E.g., the name of the header file can be used for this
purpose, in capitals, with an underscore character instead of a dot.
<p>
Apart from all this, the custom has evolved to give <strong>C</strong> header files the
extension <a name="an124"></a>
<code>.h</code>, and to give <code>C++</code> header files <em>no</em> extension. For
example, the standard <em>iostreams</em> <code>cin, cout</code> and <code>cerr</code> are available
after including the preprocessor directive <a name="an125"></a>
<code>#include &lt;iostream&gt;</code>, rather
than <code>#include &lt;iostream.h&gt;</code> in a source. In the Annotations this convention
is used with the standard <strong>C++</strong> header files, but not everywhere else
(Frankly, we tend not to follow this convention: our <strong>C++</strong> header files
still have the <code>.h</code> extension, and apparently nobody cares...).
<p>
There is more to be said about header files. In section <a href="cplusplus06.html#CLASSHEADER">6.6</a> the
preferred organization of <strong>C++</strong> header files is discussed.
<p>
<a name="LOCALVARS"></a><a name="l26"></a>
<h3>2.5.10: Defining local variables</h3>
        <a name="intro/local"></a>In <strong>C</strong> <a name="an126"></a>
local variables can only be defined at the top of a function or at
the beginning of a nested block. In <strong>C++</strong> local variables can be created at
any position in the code, even between statements.
<p>
Furthermore, local variables can be defined inside some statements, just prior
to their usage. A typical example is the <code>for</code> statement:
        <pre>
    #include &lt;stdio.h&gt;

    int main()
    {
        for (register int i = 0; i &lt; 20; i++)
            printf("%d\n", i);
        return 0;
    }
</pre>
    In this code fragment the variable <code>i</code> is created inside the <code>for</code>
statement. According to the ANSI-standard, the variable does not exist prior
to the <code>for</code>-statement and not beyond the <code>for</code>-statement.  With some
older compilers, the variable continues to exist after the execution of the
<code>for</code>-statement, but a warning like
        <blockquote>
    warning: <a name="an127"></a>
name lookup of `i' changed for new ANSI `for' scoping
    using <a name="an128"></a>
obsolete binding at `i'
        </blockquote>
    will then be issued when the variable is used outside of the <code>for</code>-loop.
The implication seems clear: define a variable just before the
<code>for</code>-statement if it's to be used after that statement, otherwise the
variable can be defined inside the <code>for</code>-statement itself.
<p>
Defining <a name="an129"></a>
local variables when they're needed requires a little getting used
to. However, eventually it tends to produce more readable and often more
efficient code than defining variables at the beginning of compound
statements. We suggest the following rules <a name="an130"></a>
 of thumb for
defining local variables:
    <ul>
    <li> Local variables should be created at `intuitively right' places, such
as in the example above. This does not only entail the <code>for</code>-statement, but
also all situations where a variable is only needed, say, half-way through the
function.
    <li> More in general, variables should be defined in such a way that
their scope is as <em>limited</em> and <em>localized</em> as possible.
Local variables are not necessarily defined anymore at the
beginning of functions, following the first <code>{</code>.
    <li> It is considered good practice to <a name="an131"></a>

    <a name="an132"></a>
<em>avoid global variables</em>. It is fairly easy to lose track of which
global variable is used for what purpose. In <strong>C++</strong> global variables are
seldomly required, and by localizing variables the well known phenomenon of
using the same variable for multiple purposes, thereby invalidating each
individual purpose of the variable, can easily be avoided.
    </ul>
<p>
If considered appropriate, <a name="an133"></a>
<em>nested blocks</em> can be used to localize
auxiliary variables. However, situations exist where local variables are
considered appropriate inside nested statements. The just mentioned <code>for</code>
statement is of course a case in point, but local variables can also be
defined within the condition clauses of <code>if-else</code> statements, within
selection clauses of <code>switch</code> statements and condition clauses of <code>while</code>
statements. Variables thus defined will be available in the full
statement, including its nested statements. For example, consider the
following <code>switch</code> statement:
        <pre>
    #include &lt;stdio.h&gt;

    int main()
    {
        switch (int c = getchar())
        {
            case 'a':
            case 'e':
            case 'i':
            case 'o':
            case 'u':
                printf("Saw vowel %c\n", c);
            break;

            case EOF:
                printf("Saw EOF\n");
            break;

            default:
                printf("Saw other character, hex value 0x%2x\n", c);
        }
    }
</pre>
    Note the location of the definition of the character `<code>c</code>': it is
defined in the expression part of the <code>switch()</code> statement. This implies
that `<code>c</code>' is available <em>only</em> in the <code>switch</code> statement itself,
including its nested (sub)statements, but not outside the scope of the
<code>switch</code>.
<p>
The same approach can be used with <code>if</code> and <code>while</code> statements: a
variable that is defined in the condition part of an <code>if</code> and <code>while</code>
statement is available in their nested statements. However, one should realize
that:
    <ul>
    <li> The variable definition should result in a variable which is
initialized to a numerical or logical value;
    <li> The variable definition cannot be nested (e.g., using parentheses)
within a more complex expression.
    </ul>
    The latter point of attention should come as no big surprise: in order to
be able to evaluate the logical condition of an <code>if</code> or <code>while</code> statement,
the value of the variable must be interpretable as either zero (false) or
non-zero (true). Usually this is no problem, but in <strong>C++</strong> <em>objects</em> (like
objects of the type <code>std::string</code> (cf. chapter <a href="cplusplus04.html#String">4</a>)) are often
returned by functions. Such objects may or may not be interpretable as
numerical values. If not (as is the case with <code>std::string</code> objects), then
such variables can <em>not</em> be defined in the condition or expression parts of
condition- or repetition statements. The following example will, therefore,
<em>not</em> compile:
        <pre>
    if (std::string myString = getString())     // assume getString() returns
    {                                           // a std::string value
        // process myString
    }
</pre>
<p>
The above deserves further clarification. Often a variable can profitably
be given local scope, but an extra check is required immediately following its
initialization. Both the initialization and the test cannot be combined in one
expression, but two nested statements are required. The following example will
therefore <em>not</em> compile either:
        <pre>
    if ((int c = getchar()) &amp;&amp; strchr("aeiou", c))
        printf("Saw a vowel\n");
</pre>
    If such a situation occurs, either use two nested <code>if</code> statements, or
localize the definition of <code>int c</code> using a nested compound statement.
Actually, other approaches are possible as well, like using <em>exceptions</em>
(cf. chapter <a href="cplusplus08.html#EXCEPTIONS">8</a>) and specialized functions, but that's jumping a
bit too far ahead. At this point in our discussion, we can suggest one of the
following approaches to remedy the problem introduced by the last example:
        <pre>
    if (int c = getchar())             // nested if-statements
        if (strchr("aeiou", c))
            printf("Saw a vowel\n");

    {                                   // nested compound statement
        int c = getchar();
        if (c &amp;&amp; strchr("aeiou", c))
        printf("Saw a vowel\n");
    }
</pre>
<p>
<a name="FunctionOverloading"></a><a name="l27"></a>
<h3>2.5.11: Function Overloading</h3>
        <a name="intro/overload"></a>In <strong>C++</strong> it is possible to define
    <a name="an134"></a>
functions having identical names but performing different actions. The
functions must differ in their <a name="an135"></a>
 parameter lists (and/or in
their <a name="an136"></a>
 <code>const</code> attribute). An example is given
below:
        <pre>
    #include &lt;stdio.h&gt;

    void show(int val)
    {
        printf("Integer: %d\n", val);
    }

    void show(double val)
    {
        printf("Double: %lf\n", val);
    }

    void show(char *val)
    {
        printf("String: %s\n", val);
    }

    int main()
    {
        show(12);
        show(3.1415);
        show("Hello World\n!");
    }
</pre>
    In the above fragment three functions <code>show()</code> are defined, which only
differ in their parameter lists: <code>int</code>, <code>double</code> and <code>char *</code>. The
functions have identical names. The definition of several functions having
identical names is called `<a name="an137"></a>
function overloading'.
<p>
It is interesting that the way in which the <strong>C++</strong> compiler implements
function overloading is quite simple. Although the functions share the same
name in the source text (in this example <code>show()</code>), the compiler (and hence
the linker) use quite different names. The conversion of a name in the source
file to an internally used name is called `<a name="an138"></a>
name mangling'. E.g., the
<strong>C++</strong> compiler might convert the name <code>void</code> <code>show</code> <code>(int)</code> to the
internal name <code>VshowI</code>, while an analogous function with a <code>char*</code>
argument might be called <code>VshowCP</code>. The actual names which are internally
used depend on the compiler and are not relevant for the programmer, except
where these names show up in e.g., a listing of the contents of a library.
<p>
A few remarks concerning function overloading are:
    <ul>
    <li> Do not use function overloading for functions doing conceptually
different tasks.  In the example above, the functions <code>show()</code> are still
somewhat related (they print information to the screen).
<p>
However, it is also quite possible to define two functions <code>lookup()</code>,
one of which would find a name in a list while the other would determine the
video mode. In this case the two functions have nothing in common except for
their name. It would therefore be more practical to use names which suggest
the action; say, <code>findname()</code> and <code>vidmode()</code>.
    <li> <strong>C++</strong> does not allow identically named functions to differ only in
their return value, as it is always the programmer's choice to either use or
ignore the return value of a function. E.g., the fragment
        <pre>
    printf("Hello World!\n");
</pre>
    holds no information concerning the return value of the function
<code>printf()</code>. Two functions <code>printf()</code> which would only differ in their
return type could therefore not be distinguished by the compiler.
    <li> Function overloading can produce surprises. E.g., imagine a
    statement like
        <pre>
    show(0);
</pre>
    given the three functions <code>show()</code> above. The zero could be interpreted
here as a <code>NULL</code> pointer to a <code>char</code>, i.e., a <code>(char *)0</code>, or as an
integer with the value zero. Here, <strong>C++</strong> will call the function
expecting an integer argument, which might not be what one expects.
    <li> In chapter <a href="cplusplus06.html#Classes">6</a> the notion of <code>const</code> member functions will
be introduced (cf. section <a href="cplusplus06.html#ConstFunctions">6.2</a>). Here it is merely mentioned
that classes normally have so-called member functions associated with them
(see, e.g., chapter <a href="cplusplus04.html#String">4</a> for an informal introduction of the
concept). Apart from
    <a name="an139"></a>

    overloading member functions using different parameter lists, it
is then also possible to
    <a name="an140"></a>

    overload member functions by their <code>const</code>
attributes. In those cases, classes may have pairs of identically named member
functions, having identical parameter lists. Then, these functions are
overloaded by their <code>const</code> attribute: one of these function must
have the <code>const</code> attribute, and the other must not.
    </ul>
<p>
<a name="l28"></a>
<h3>2.5.12: Default function arguments</h3>
        <a name="intro/default"></a>In <strong>C++</strong> it is possible to provide `<a name="an141"></a>
default arguments' when defining a
function. These arguments are supplied by the compiler when they are not
specified by the programmer. For example:
        <pre>
    #include &lt;stdio.h&gt;

    void showstring(char *str = "Hello World!\n");

    int main()
    {
        showstring("Here's an explicit argument.\n");

        showstring();           // in fact this says:
                                // showstring("Hello World!\n");
    }
</pre>
    The possibility to omit arguments in situations where default arguments
are defined is just a nice touch: the compiler will supply the missing
argument unless explicitly specified in the call. The code of the program
becomes by no means shorter or more efficient.
<p>
Functions may be defined with more than one default argument:
        <pre>
    void two_ints(int a = 1, int b = 4);

    int main()
    {
        two_ints();            // arguments:  1, 4
        two_ints(20);          // arguments: 20, 4
        two_ints(20, 5);       // arguments: 20, 5
    }
</pre>
    When the function <code>two_ints()</code> is called, the compiler supplies one or
two arguments when necessary. A statement as <code>two_ints(,6)</code> is however not
allowed: when arguments are omitted they must be on the right-hand side.
<p>
Default arguments must be known at <a name="an142"></a>
compile-time, since at that moment
arguments are supplied to functions. Therefore,  the
default arguments must be mentioned in the function's <em>declaration</em>,
rather than in its <em>implementation</em>:
        <pre>
    // sample header file
    extern void two_ints(int a = 1, int b = 4);

    // code of function in, say, two.cc
    void two_ints(int a, int b)
    {
        ...
    }
</pre>
    Note that supplying the default arguments in function definitions instead
of in function declarations in header files is incorrect: when the function is
used in other sources the compiler will read the header file and not the
function definition. Consequently, in those cases the compiler has no way to
determine the values of default function arguments. Current compilers may
generate errors when detecting default arguments in function definitions.
<p>
<a name="l29"></a>
<h3>2.5.13: The keyword `typedef'</h3>
        <a name="intro/typedef"></a>The keyword <a name="an143"></a>
<code>typedef</code> is still allowed in <strong>C++</strong>, but is not required
anymore when defining  <a name="an144"></a>
<code>union</code>, <a name="an145"></a>
<code>struct</code> or <a name="an146"></a>
<code>enum</code> definitions.
This is illustrated in the following example:
        <pre>
    struct somestruct
    {
        int     a;
        double  d;
        char    string[80];
    };
</pre>
    When a <code>struct</code>, <code>union</code> or other compound type is defined, the tag of
this type can be used as type name (this is <code>somestruct</code> in the above
example):
        <pre>
    somestruct what;

    what.d = 3.1415;
</pre>
<p>
<a name="FunctionInStruct"></a><a name="l30"></a>
<h3>2.5.14: Functions as part of a struct</h3>
        <a name="intro/struct"></a>In <strong>C++</strong> it is allowed to define <a name="an147"></a>
functions as part of a struct. Here we
encounter the first concrete example of an object: as previously was described
(see section <a href="cplusplus02.html#OOP">2.4</a>), an <a name="an148"></a>
object is a structure containing all involved
code and data.
<p>
A definition of a <code>struct point</code> is given in the code fragment below.
In this structure, two <code>int</code> data fields and one function <code>draw()</code> are
declared.
        <pre>
    struct point            // definition of a screen
    {                       // dot:
        int x;              // coordinates
        int y;              // x/y
        void draw(void);    // drawing function
    };
</pre>
    A similar structure could be part of a painting program and could, e.g.,
represent a pixel in the drawing. With respect to this <code>struct</code> it should be
noted that:
    <ul>
    <li> The function <code>draw()</code> mentioned in the <code>struct</code> definition is a
mere <em>declaration</em>. The actual code of the function, or in other words the
actions performed by the function, are located elsewhere. We will describe the
actual definitions of functions inside <code>struct</code>s later (see section
<a href="cplusplus03.html#FunctionsInStructs">3.2</a>).
    <li> The size of the <code>struct</code> <code>point</code> is equal to the size of its
two <code>int</code>s.  A function declared inside the structure does not affect its
size. The compiler implements this behavior by allowing the function
<code>draw()</code> to be known only in the context of a <code>point</code>.
    </ul>
    The <code>point</code> structure could be used as follows:
        <pre>
    point a;                // two points on
    point b;                // the screen

    a.x = 0;                // define first dot
    a.y = 10;               // and draw it
    a.draw();

    b = a;                  // copy a to b
    b.y = 20;               // redefine y-coord
    b.draw();               // and draw it
</pre>
    The function that is part of the structure is selected in a similar
manner in which data fields are selected; i.e., using the
    <a name="an149"></a>
field selector operator (<code>.</code>). When pointers to <code>struct</code>s are used,
<code>-&gt;</code> can be used.
<p>
The idea behind this syntactical construction is that several types may
contain <a name="an150"></a>
functions having identical names. E.g., a structure representing a
circle might contain three <code>int</code> values: two values for the coordinates of
the center of the circle and one value for the radius. Analogously to the
<code>point</code> structure, a function <code>draw()</code> could be declared which would draw
the circle.
<p>

<hr>
<ul>
    <li> <a href="cplusplus.html">Table of Contents</a>
    <li> <a href="cplusplus01.html">Previous Chapter</a>
    <li> <a href="cplusplus03.html">Next Chapter</a>
</ul>
<hr>
</body>
</html>
